package com.example.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.login.UserDetailsImpl;
import com.example.mapper.UserMapper;
import com.example.module.User;
import com.example.utils.Fastjson2ConverterUtils;
import com.example.utils.JwtUtils;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate<String,String> redisTemplate;
    @Resource
    private AuthenticationManager authenticationManager;

    public User selectByName(String userName){
        LambdaQueryWrapper<User> query = new LambdaQueryWrapper<>();
        query.eq(User :: getName,userName);

        return userMapper.selectOne(query);
    }

    public Map<String,String> login(User user){

        //
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getName(),user.getPassword());
        Authentication authentication = authenticationManager.authenticate(usernamePasswordAuthenticationToken);

        UserDetailsImpl userDetails = (UserDetailsImpl)authentication.getPrincipal();

        String userId = String.valueOf(userDetails.getUser().getId());
        String jwt = JwtUtils.userIdToJwt(userId);

        redisTemplate.opsForValue().set(userId, Fastjson2ConverterUtils.toJson(userDetails.getUser()));

        Map<String,String> result = new HashMap<>();
        result.put("token",jwt);
        return result;
    }
}
